﻿using BW.Mes.WinForms.BasicData;
using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static BW.Mes.WinForms.BasicData.LineForm1;

namespace BW.Mes.WinForms.BasicData
{
    public partial class LineForm1 : DevExpress.XtraEditors.XtraForm
    {
        private readonly HttpClient _httpClient;
        private readonly string _lineApiBaseUrl = "http://120.26.197.100:8022";
        private List<LineModel> _allLines = new List<LineModel>();

        public LineForm1()
        {
            InitializeComponent();
            // 设置产线管理列表为淡黄色渐变背景色
            gridView1.Appearance.Row.BackColor = ColorTranslator.FromHtml("#fff9d1");
            gridView1.Appearance.Row.BackColor2 = ColorTranslator.FromHtml("#fff6e0");
            gridView1.Appearance.Row.Options.UseBackColor = true;
            // 可选：设置表头同色
            gridView1.Appearance.HeaderPanel.BackColor = ColorTranslator.FromHtml("#fff9d1");
            gridView1.Appearance.HeaderPanel.Options.UseBackColor = true;
            // 产线管理斑马纹：偶数行#fffbe0（亮黄色），奇数行#fffde6（极浅黄色）
            gridView1.OptionsView.EnableAppearanceEvenRow = true;
            gridView1.OptionsView.EnableAppearanceOddRow = true;
            gridView1.Appearance.EvenRow.BackColor = ColorTranslator.FromHtml("#fffbe0");
            gridView1.Appearance.EvenRow.Options.UseBackColor = true;
            gridView1.Appearance.OddRow.BackColor = ColorTranslator.FromHtml("#fffde6");
            gridView1.Appearance.OddRow.Options.UseBackColor = true;
            gridView1.Appearance.FocusedRow.BackColor = Color.Transparent;
            gridView1.Appearance.FocusedRow.Options.UseBackColor = false;
            gridView1.Appearance.HideSelectionRow.BackColor = Color.Transparent;
            gridView1.Appearance.HideSelectionRow.Options.UseBackColor = false;
            // 禁用皮肤影响
            gridControl1.LookAndFeel.UseDefaultLookAndFeel = false;
            //初始化httpClient
            _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            // 窗体加载时获取数据
            this.Load += LineForm1_Load;
            gridView1.CustomUnboundColumnData += gridView1_CustomUnboundColumnData;
            // 启用多选复选框
            gridView1.OptionsSelection.MultiSelect = true;
            gridView1.OptionsSelection.MultiSelectMode = DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode.CheckBoxRowSelect;
        }
        // 1. 分页DTO
        public class LinePageResult
        {
            public int totalCount { get; set; }
            public List<LineModel> pageDatas { get; set; }
            public string message { get; set; }
            public object data { get; set; }
            public int code { get; set; }
        }
        // 2. 分页数据加载方法
        private async Task LoadLineData(int pageIndex, int pageSize)
        {
            try
            {
                string url = $"T2/Line/GetLine?PageIndex={pageIndex}&PageSize={pageSize}";
                LinePageResult result = null;
                List<LineModel> data = null;
                int totalCount = pagerControl1.TotalCount; // 默认保留原有总数
                try
                {
                    result = await GetApiDataAsync<LinePageResult>(url);
                    data = result?.pageDatas ?? new List<LineModel>();
                    totalCount = result?.totalCount ?? 0;
                }
                catch
                {
                    // 如果返回的是数组
                    data = await GetApiDataAsync<List<LineModel>>(url);
                    // totalCount 不变，避免分页控件失效
                }
                gridControl1.DataSource = data;
                pagerControl1.TotalCount = totalCount;
                pagerControl1.PageIndex = pageIndex;
                pagerControl1.PageSize = pageSize;
                gridView1.PopulateColumns();
                var idColumn = gridView1.Columns["Id"];
                if (idColumn != null) idColumn.Visible = false;
                EnsureSerialNumberColumn();
                gridView1.BestFitColumns();
                gridView1.RefreshData();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载数据失败: {ex.Message}", "错误");
            }
        }
        /// <summary>
        /// 获取产线
        /// </summary>
        private async Task<T> GetApiDataAsync<T>(string endpoint)
        {
            try
            {
                HttpResponseMessage response = await _httpClient.GetAsync($"{_lineApiBaseUrl}/{endpoint}");
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<T>(responseBody);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        // 提交数据到API
        public async Task<bool> PostApiDataAsync<T>(string endpoint, T data)
        {
            try
            {
                string jsonData = JsonConvert.SerializeObject(data);
                HttpContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");
                HttpResponseMessage response = await _httpClient.PostAsync($"{_lineApiBaseUrl}/{endpoint}", content);
                response.EnsureSuccessStatusCode();
                return true;
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"提交数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }
        public class LineModel
        {
            public long Id { get; set; }
            /// <summary>
            /// 产线编号
            /// </summary>
            [DisplayName("产线编号")]
            public string LineCode { get; set; }
            /// <summary>
            /// 产线名称
            /// </summary>
            /// 
            [DisplayName("产线名称")]
            public string LineName { get; set; }

            /// <summary>
            /// 产线描述
            /// </summary>
            /// 
            [DisplayName("产线描述")]
            public string LineMsg { get; set; }
            [DisplayName("所属车间")]
            public string WorkshopName { get; set; }
            [DisplayName("创建人")]
            public string CreatedBy { get; set; }
            [DisplayName("创建时间")]
            public DateTime CreatedAt { get; set; } = DateTime.Now;
            [DisplayName("修改时间")]
            public DateTime? UpdatedAt { get; set; }
        }
        private async void simpleButton2_Click(object sender, EventArgs e)
        {
            await LoadLineData(pagerControl1.PageIndex, pagerControl1.PageSize);
        }

        private void gridControl1_Click(object sender, EventArgs e)
        {

        }


        private async void btnAdd_Click(object sender, EventArgs e)
        {
            var form = new AddLineForm();
            if (form.ShowDialog() == DialogResult.OK)
            {
                await LoadLineData(1, pagerControl1.PageSize);
            }
        }

        private async void btnEdit_Click(object sender, EventArgs e)
        {
            var selectedRows = gridView1.GetSelectedRows();
            if (selectedRows.Length != 1)
            {
                XtraMessageBox.Show("请选择一条要修改的产线！");
                return;
            }
            var line = gridView1.GetRow(selectedRows[0]) as LineModel;
            if (line == null)
            {
                XtraMessageBox.Show("未获取到产线信息！");
                return;
            }
            var form = new AddLineForm(line);
            if (form.ShowDialog() == DialogResult.OK)
            {
                await LoadLineData(pagerControl1.PageIndex, pagerControl1.PageSize);
            }
        }

        private async void btnRefresh_Click(object sender, EventArgs e)
        {
            await LoadLineData(pagerControl1.PageIndex, pagerControl1.PageSize);
        }

        private void EnsureSerialNumberColumn()
        {
            if (gridView1.Columns["序号"] == null)
            {
                var col = gridView1.Columns.AddField("序号");
                col.Caption = "序号";
                col.UnboundType = DevExpress.Data.UnboundColumnType.Integer;
                col.Visible = true;
                col.VisibleIndex = 0;
            }
            else
            {
                gridView1.Columns["序号"].Visible = true;
                gridView1.Columns["序号"].VisibleIndex = 0;
            }
        }

        private void gridView1_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            if (e.Column.FieldName == "序号" && e.IsGetData)
            {
                e.Value = e.ListSourceRowIndex + 1;
            }
        }

        private void AfterBindLineData()
        {
            EnsureSerialNumberColumn();
            var idColumn = gridView1.Columns["Id"];
            if (idColumn != null) idColumn.Visible = false;
        }

        private async void btnQuery_Click(object sender, EventArgs e)
        {
            await LoadLineData(1, pagerControl1.PageSize);
        }

        // 删除按钮事件
        private async void btnDelete_Click(object sender, EventArgs e)
        {
            var selectedRows = gridView1.GetSelectedRows();
            if (selectedRows.Length == 0)
            {
                XtraMessageBox.Show("请先选择要删除的产线！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            var confirm = XtraMessageBox.Show($"确定要删除选中的 {selectedRows.Length} 条产线吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (confirm != DialogResult.Yes) return;

            int successCount = 0;
            int failureCount = 0;
            string firstError = null;

            foreach (var rowHandle in selectedRows)
            {
                var line = gridView1.GetRow(rowHandle) as LineModel;
                if (line != null)
                {
                    var (success, errorMsg) = await DeleteLine(line.Id);
                    if (success)
                    {
                        successCount++;
                    }
                    else
                    {
                        failureCount++;
                        if (firstError == null)
                            firstError = errorMsg;
                    }
                }
            }

            await LoadLineData(pagerControl1.PageIndex, pagerControl1.PageSize);

            if (successCount > 0 && failureCount == 0)
            {
                XtraMessageBox.Show($"成功删除 {successCount} 条产线。", "操作成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else if (successCount > 0 && failureCount > 0)
            {
                XtraMessageBox.Show($"成功删除 {successCount} 条产线，{failureCount} 条删除失败。\n第一个失败原因：{firstError}", "操作完成", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else if (failureCount > 0)
            {
                XtraMessageBox.Show(firstError, "删除失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 调用API删除产线
        private async Task<(bool, string)> DeleteLine(long id)
        {
            try
            {
                var response = await _httpClient.PutAsync($"{_lineApiBaseUrl}/T2/Line/DeleteLine?id={id}", null);
                var responseContent = await response.Content.ReadAsStringAsync();
                if (response.IsSuccessStatusCode)
                {
                    var apiResult = JsonConvert.DeserializeObject<ApiResult<object>>(responseContent);
                    if (apiResult != null && apiResult.code == 200)
                    {
                        return (true, null);
                    }
                    else
                    {
                        string errorMessage = apiResult?.message ?? "删除失败，但未返回具体错误信息。";
                        return (false, errorMessage);
                    }
                }
                else
                {
                    string errorMessage = $"HTTP错误: {response.StatusCode}";
                    try
                    {
                        var errorResult = JsonConvert.DeserializeObject<ApiResult<object>>(responseContent);
                        if (errorResult != null && !string.IsNullOrEmpty(errorResult.message))
                        {
                            errorMessage = errorResult.message;
                        }
                    }
                    catch { }
                    return (false, errorMessage);
                }
            }
            catch (Exception ex)
            {
                return (false, $"删除时发生异常: {ex.Message}");
            }
        }

        // 3. 绑定分页控件事件和初始化
        private async void LineForm1_Load(object sender, EventArgs e)
        {
            pagerControl1.PageChanged += async (s, e2) =>
            {
                await LoadLineData(pagerControl1.PageIndex, pagerControl1.PageSize);
            };
            await LoadLineData(1, pagerControl1.PageSize);
        }
    }
}